package test

import (
	"github.com/IBM/sarama"
	"github.com/spf13/viper"
	"log"
	"os"
	"os/signal"
	"sync"
)

// 暂时无用到
func KafkaProducer2() {
	config := sarama.NewConfig()
	//sarama.Logger = log{}
	//cfg := sarama.NewConfig()
	//cfg.Version = sarama.V2_2_0_0
	//cfg.Producer.Return.Errors = true
	//cfg.Net.SASL.Enable = false
	//cfg.Producer.Return.Successes = true //这个是关键，否则读取不到消息
	//cfg.Producer.RequiredAcks = sarama.WaitForAll
	//cfg.Producer.Partitioner = sarama.NewManualPartitioner //允许指定分组
	//cfg.Consumer.Return.Errors = true
	//cfg.Consumer.Offsets.Initial = sarama.OffsetOldest
	////cfg.Group.Return.Notifications = true
	//cfg.ClientID = "service-exchange-api"

	config.Producer.Return.Successes = true //这个是关键，否则读取不到消息
	config.Producer.Partitioner = sarama.NewRandomPartitioner
	config.Producer.RequiredAcks = -1
	//client, err := sarama.NewClient([]string{"192.168.0.104:9092", "localhost:9292", "localhost:9392"}, config)
	client, err := sarama.NewClient(viper.GetStringSlice("receive.kafka.brokerIpPort"), config)
	defer client.Close()
	if err != nil {
		panic(err)
	}
	producer, err := sarama.NewAsyncProducerFromClient(client)
	if err != nil {
		panic(err)
	}

	// Trap SIGINT to trigger a graceful shutdown.
	signals := make(chan os.Signal, 1)
	signal.Notify(signals, os.Interrupt)

	var (
		wg                          sync.WaitGroup
		enqueued, successes, errors int
	)

	wg.Add(1)
	// start a groutines to count successes num
	go func() {
		defer wg.Done()
		for range producer.Successes() {
			successes++
		}
	}()

	wg.Add(1)
	// start a groutines to count error num
	go func() {
		defer wg.Done()
		for err := range producer.Errors() {
			log.Println(err)
			errors++
		}
	}()
ProducerLoop:
	for {
		message := &sarama.ProducerMessage{Topic: "my_topic", Value: sarama.StringEncoder("testing 123")}
		select {
		case producer.Input() <- message:
			enqueued++

		case <-signals:
			producer.AsyncClose() // Trigger a shutdown of the producer.
			break ProducerLoop
		}
	}

	wg.Wait()

	log.Printf("Successfully produced: %d; errors: %d\n", successes, errors)
}
